"""
Utility functions for the Three.js to GIF converter.
Provides helper functions for path validation, logging setup, and configuration management.
"""

import json
import logging
from pathlib import Path
from typing import Union, Dict, Any

def setup_logging(config):
    """Configure logging settings with detailed formatting."""
    logging.basicConfig(
        level=config['logging']['level'],
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

def get_project_root() -> Path:
    """Get the project root directory."""
    return Path(__file__).parent.parent

def resolve_path(path: Union[str, Path], relative_to: Union[str, Path] = None) -> Path:
    """
    Resolve a path relative to the project root or specified directory.
    
    Args:
        path: Path to resolve
        relative_to: Optional base directory to resolve relative to
        
    Returns:
        Resolved absolute Path
    """
    if relative_to is None:
        relative_to = get_project_root()
    
    path = Path(path)
    if not path.is_absolute():
        path = Path(relative_to) / path
    
    return path.absolute()

def load_config(config_path: Union[str, Path]) -> Dict[str, Any]:
    """
    Load and validate configuration from JSON file.
    
    Args:
        config_path: Path to configuration file
        
    Returns:
        Dict containing validated configuration
        
    Raises:
        FileNotFoundError: If config file doesn't exist
        ValueError: If config is invalid
    """
    config_path = Path(config_path)
    if not config_path.exists():
        raise FileNotFoundError(f"Configuration file not found: {config_path}")
        
    with open(config_path) as f:
        config = json.load(f)
        
    # Ensure required fields exist
    required_fields = ['html_file', 'output_gif', 'frames', 'resolution', 'frame_delay']
    missing_fields = [field for field in required_fields if field not in config]
    if missing_fields:
        raise ValueError(f"Missing required configuration fields: {missing_fields}")
        
    # Set default chrome_driver config if not present
    if 'chrome_driver' not in config:
        config['chrome_driver'] = {
            'path': None,
            'auto_download': True,
            'download_timeout': 30
        }
        
    return config

